package com.example.appstorenew;

import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.appstorenew.adapter.appRecommendAdapter;
import com.example.appstorenew.pojo.appRecommend;
import com.example.appstorenew.utils.AppRecommendUtil;
import com.example.appstorenew.utils.TokenUtil;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
    List<appRecommend> appRecommendList;
    GridView gv_appsinsearch;
    String token;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        Button bt_searchinsearch = findViewById(R.id.bt_searchinsearch);
        bt_searchinsearch.setOnClickListener(this);

        EditText et_search = findViewById(R.id.et_search);


        //适配器填满APP推荐列表
        gv_appsinsearch = findViewById(R.id.gv_appsinsearch);
        new Thread(()->{
            try {
                token = TokenUtil.getToken();
                appRecommendList = AppRecommendUtil.getAppRecommendList(token);

                runOnUiThread(()->{
                    appRecommendAdapter appRecommendAdapter = new appRecommendAdapter(this,appRecommendList);
                    gv_appsinsearch.setAdapter(appRecommendAdapter);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
    }


    @Override
    public void onClick(View v) {
        EditText et_search = findViewById(R.id.et_search);
        String searchWord = et_search.getText().toString();

        new Thread(()->{
            List<appRecommend> list_search = new ArrayList<>();
            try {

                for (int i = 0; i < appRecommendList.size(); i++) {
                    if(appRecommendList.get(i).getApkName().contains(searchWord)){
                        list_search.add(appRecommendList.get(i));
                        break;
                    }
                }

                runOnUiThread(()->{
                    if("".equals(searchWord) | searchWord == null){
                        appRecommendAdapter appRecommendAdapter = new appRecommendAdapter(this,appRecommendList);
                        gv_appsinsearch.setAdapter(appRecommendAdapter);
                    }else{
                        appRecommendAdapter appRecommendAdapter = new appRecommendAdapter(this,list_search);
                        gv_appsinsearch.setAdapter(appRecommendAdapter);
                    }

                });
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
    }
}